// 游戏常量
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const MOBILE_SCALE_FACTOR = 0.8; // 移动端缩放因子

// Three.js相关变量
let scene, camera, renderer;
let gameBoard = [];
let currentPiece;
let score = 0;
let level = 1;
let isGameOver = false;
let isPaused = false;
let lastDropTime = 0;

// 初始化Three.js场景
function initThreeJS() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x000000); // 添加黑色背景

  // 根据设备宽度调整大小
  const isMobile = window.innerWidth <= 768;
  const gameWidth = isMobile ? window.innerWidth * MOBILE_SCALE_FACTOR : COLS * BLOCK_SIZE;
  const gameHeight = isMobile ? (window.innerWidth * MOBILE_SCALE_FACTOR * (ROWS / COLS)) : ROWS * BLOCK_SIZE;

  camera = new THREE.PerspectiveCamera(75, gameWidth / gameHeight, 0.1, 1000);
  renderer = new THREE.WebGLRenderer({
    canvas: document.getElementById('gameCanvas'),
    antialias: true
  });

  renderer.setSize(gameWidth, gameHeight);
  camera.position.z = isMobile ? 20 : 15;

  // 添加环境光
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(ambientLight);

  // 添加方向光
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
  directionalLight.position.set(10, 10, 10);
  scene.add(directionalLight);

  // 初始化游戏板
  gameBoard = Array(ROWS).fill().map(() => Array(COLS).fill(0));

  // 渲染一次场景
  renderer.render(scene, camera);
}

// 方块形状定义
const SHAPES = [
  // I形
  [[1, 1, 1, 1]],
  // L形
  [[1, 0], [1, 0], [1, 1]],
  // J形
  [[0, 1], [0, 1], [1, 1]],
  // O形
  [[1, 1], [1, 1]],
  // Z形
  [[1, 1, 0], [0, 1, 1]],
  // S形
  [[0, 1, 1], [1, 1, 0]],
  // T形
  [[1, 1, 1], [0, 1, 0]]
];

// 创建新方块
function createNewPiece() {
  const shape = SHAPES[Math.floor(Math.random() * SHAPES.length)];
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = new THREE.MeshPhongMaterial({
    color: getRandomColor(),
    shininess: 50
  });

  const piece = {
    shape: shape,
    position: { x: Math.floor(COLS / 2) - Math.floor(shape[0].length / 2), y: 0 },
    mesh: new THREE.Group()
  };

  // 根据形状创建方块组
  for (let y = 0; y < shape.length; y++) {
    for (let x = 0; x < shape[y].length; x++) {
      if (shape[y][x]) {
        const cube = new THREE.Mesh(geometry, material);
        cube.scale.set(BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        cube.position.set(
          x * BLOCK_SIZE,
          -y * BLOCK_SIZE,
          0
        );
        piece.mesh.add(cube);
      }
    }
  }

  piece.mesh.position.set(
    piece.position.x * BLOCK_SIZE,
    -piece.position.y * BLOCK_SIZE,
    0
  );
  scene.add(piece.mesh);
  return piece;
}

// 获取随机颜色
function getRandomColor() {
  const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff];
  return colors[Math.floor(Math.random() * colors.length)];
}

// 游戏主循环
function gameLoop(currentTime) {
  if (!lastDropTime) lastDropTime = currentTime;

  const dropInterval = 1000 / level; // 随等级加快
  if (currentTime - lastDropTime > dropInterval) {
    if (!isPaused && !isGameOver) {
      movePieceDown();
    }
    lastDropTime = currentTime;
  }

  if (currentPiece) {
    renderer.render(scene, camera);
  }

  if (!isGameOver) {
    requestAnimationFrame(gameLoop);
  }
}

// 初始化游戏
function init() {
  initThreeJS();
  document.getElementById('startBtn').addEventListener('click', startGame);
  document.getElementById('pauseBtn').addEventListener('click', togglePause);
  document.addEventListener('keydown', handleKeyPress);

  // 添加触控按钮事件
  document.getElementById('leftBtn')?.addEventListener('touchstart', movePieceLeft);
  document.getElementById('rightBtn')?.addEventListener('touchstart', movePieceRight);
  document.getElementById('downBtn')?.addEventListener('touchstart', movePieceDown);
  document.getElementById('rotateBtn')?.addEventListener('touchstart', rotatePiece);

  // 防止触控滑动
  document.addEventListener('touchmove', (e) => e.preventDefault(), { passive: false });
}

// 开始游戏
function startGame() {
  // 重置游戏状态
  resetGame();

  // 创建新方块
  currentPiece = createNewPiece();

  // 开始游戏循环
  lastDropTime = 0;
  isGameOver = false;
  requestAnimationFrame(gameLoop);
}

// 处理键盘输入
function handleKeyPress(event) {
  if (isGameOver || isPaused) return;

  switch (event.keyCode) {
    case 37: // 左箭头
      movePieceLeft();
      break;
    case 39: // 右箭头
      movePieceRight();
      break;
    case 40: // 下箭头
      movePieceDown();
      break;
    case 38: // 上箭头
      rotatePiece();
      break;
    case 32: // 空格
      dropPiece();
      break;
  }
}

// 更新分数
function updateScore() {
  document.getElementById('score').textContent = score;
  document.getElementById('level').textContent = level;
}

// 添加重置游戏函数
function resetGame() {
  // 重置游戏状态
  score = 0;
  level = 1;
  isGameOver = false;
  isPaused = false;
  lastDropTime = 0;

  // 清空游戏板
  gameBoard = Array(ROWS).fill().map(() => Array(COLS).fill(0));

  // 清除场景中的所有方块
  while (scene.children.length > 0) {
    scene.remove(scene.children[0]);
  }

  // 重新添加光源
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(ambientLight);
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
  directionalLight.position.set(10, 10, 10);
  scene.add(directionalLight);

  // 更新分数显示
  updateScore();
}

// 添加暂停切换函数
function togglePause() {
  isPaused = !isPaused;
  document.getElementById('pauseBtn').textContent = isPaused ? '继续' : '暂停';
}

// 添加移动方块的基本函数
function movePieceLeft() {
  if (currentPiece && canMove(-1, 0)) {
    currentPiece.position.x--;
    updatePiecePosition();
  }
}

function movePieceRight() {
  if (currentPiece && canMove(1, 0)) {
    currentPiece.position.x++;
    updatePiecePosition();
  }
}

function movePieceDown() {
  if (currentPiece && canMove(0, 1)) {
    currentPiece.position.y++;
    updatePiecePosition();
  } else {
    lockPiece();
    currentPiece = createNewPiece();
  }
}

// 实现碰撞检测函数
function canMove(deltaX, deltaY) {
  if (!currentPiece) return false;

  const newX = currentPiece.position.x + deltaX;
  const newY = currentPiece.position.y + deltaY;

  for (let y = 0; y < currentPiece.shape.length; y++) {
    for (let x = 0; x < currentPiece.shape[y].length; x++) {
      if (currentPiece.shape[y][x]) {
        const boardX = newX + x;
        const boardY = newY + y;

        // 检查边界
        if (boardX < 0 || boardX >= COLS || boardY >= ROWS) {
          return false;
        }

        // 检查碰撞
        if (boardY >= 0 && gameBoard[boardY][boardX]) {
          return false;
        }
      }
    }
  }
  return true;
}

// 修改更新方块位置函数
function updatePiecePosition() {
  if (currentPiece && currentPiece.mesh) {
    currentPiece.mesh.position.x = currentPiece.position.x * BLOCK_SIZE;
    currentPiece.mesh.position.y = -currentPiece.position.y * BLOCK_SIZE;
  }
}

// 实现旋转方块函数
function rotatePiece() {
  if (!currentPiece) return;

  const rotated = [];
  const M = currentPiece.shape.length;
  const N = currentPiece.shape[0].length;

  // 创建旋转后的矩阵
  for (let x = 0; x < N; x++) {
    rotated[x] = [];
    for (let y = 0; y < M; y++) {
      rotated[x][y] = currentPiece.shape[M - 1 - y][x];
    }
  }

  // 保存原始形状
  const originalShape = currentPiece.shape;
  currentPiece.shape = rotated;

  // 检查旋转后是否有碰撞
  if (!canMove(0, 0)) {
    currentPiece.shape = originalShape;
    return;
  }

  // 更新3D模型
  scene.remove(currentPiece.mesh);
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = currentPiece.mesh.children[0].material;

  const newMesh = new THREE.Group();
  for (let y = 0; y < rotated.length; y++) {
    for (let x = 0; x < rotated[y].length; x++) {
      if (rotated[y][x]) {
        const cube = new THREE.Mesh(geometry, material);
        cube.scale.set(BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        cube.position.set(
          x * BLOCK_SIZE,
          -y * BLOCK_SIZE,
          0
        );
        newMesh.add(cube);
      }
    }
  }

  currentPiece.mesh = newMesh;
  scene.add(currentPiece.mesh);
  updatePiecePosition();
}

// 实现锁定方块函数
function lockPiece() {
  if (!currentPiece) return;

  // 将当前方块添加到游戏板
  for (let y = 0; y < currentPiece.shape.length; y++) {
    for (let x = 0; x < currentPiece.shape[y].length; x++) {
      if (currentPiece.shape[y][x]) {
        const boardX = currentPiece.position.x + x;
        const boardY = currentPiece.position.y + y;
        if (boardY >= 0) {
          gameBoard[boardY][boardX] = 1;
        } else {
          // 游戏结束
          isGameOver = true;
          alert('游戏结束！得分：' + score);
          return;
        }
      }
    }
  }

  // 保持方块在场景中
  currentPiece = null;
  checkLines();
}

// 添加检查行消除函数
function checkLines() {
  let linesCleared = 0;

  for (let y = ROWS - 1; y >= 0; y--) {
    if (gameBoard[y].every(cell => cell === 1)) {
      // 消除该行
      gameBoard.splice(y, 1);
      gameBoard.unshift(new Array(COLS).fill(0));
      linesCleared++;

      // 更新3D显示
      updateBoardDisplay();

      y++; // 重新检查当前行，因为上面的行下移了
    }
  }

  if (linesCleared > 0) {
    score += linesCleared * 100 * level;
    level = Math.floor(score / 1000) + 1;
    updateScore();
  }
}

// 添加更新游戏板显示的函数
function updateBoardDisplay() {
  // 清除现有的固定方块
  const children = [...scene.children];
  children.forEach(child => {
    if (child instanceof THREE.Group && child !== currentPiece?.mesh) {
      scene.remove(child);
    }
  });

  // 重新创建固定方块的显示
  const geometry = new THREE.BoxGeometry(1, 1, 1);

  for (let y = 0; y < ROWS; y++) {
    for (let x = 0; x < COLS; x++) {
      if (gameBoard[y][x]) {
        const material = new THREE.MeshPhongMaterial({
          color: 0x808080 // 使用灰色表示固定的方块
        });

        const cube = new THREE.Mesh(geometry, material);
        cube.scale.set(BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        cube.position.set(
          x * BLOCK_SIZE,
          -y * BLOCK_SIZE,
          0
        );

        const group = new THREE.Group();
        group.add(cube);
        scene.add(group);
      }
    }
  }
}

// 初始化
init(); 